package com.fattyCorps.game.config.game;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fattyCorps.game.mapper.GlobalMailMapper;
import com.fattyCorps.game.mgr.event.EEvent;
import com.fattyCorps.game.obj.mould.GlobalMailMould;
import com.fattyCorps.game.an.AEventListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

@Component
@Slf4j
public class GlobalMailConfig {
    private CopyOnWriteArrayList<GlobalMailMould> globalMailMouldList = new CopyOnWriteArrayList<>();
    private int maxGlobalMailId = 0;

    @Autowired
    GlobalMailMapper globalMailMapper;

    public int getMaxGlobalMailId() {
        return maxGlobalMailId;
    }

    public List<GlobalMailMould> getDisGlobalMailList(int globalMailId) {
        List<GlobalMailMould> retList = new ArrayList<>();
        for (GlobalMailMould globalMailMould : globalMailMouldList) {
            if (globalMailMould.getId() > globalMailId) {
                retList.add(globalMailMould);
            }
        }

        return retList;
    }

    public void addGlobalMailInDb(String title, String content, String attachment) {
        GlobalMailMould globalMailMould = new GlobalMailMould();
        globalMailMould.setTitle(title);
        globalMailMould.setContent(content);
        globalMailMould.setAttachment(attachment);

        globalMailMapper.insert(globalMailMould);
        globalMailMouldList.add(globalMailMould);
        maxGlobalMailId = globalMailMould.getId();
    }

    @AEventListener(EEvent.EVENT_ON_SERVER_START)
    public void reload() {
        QueryWrapper<GlobalMailMould> wrapper = new QueryWrapper<>();
        List<GlobalMailMould> globalMailMoulds = globalMailMapper.selectList(wrapper);

        globalMailMouldList.clear();
        this.globalMailMouldList.addAll(globalMailMoulds);

        for (GlobalMailMould globalMailMould : globalMailMoulds) {
            if (maxGlobalMailId < globalMailMould.getId()) {
                maxGlobalMailId = globalMailMould.getId();
            }
        }
    }
}
